package com.lgmshare.component.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.PermissionChecker;

import com.lgmshare.component.R;

import java.lang.reflect.Method;

/**
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2016/5/30 9:59
 */
public class PermissionCheckUtils {

    private PermissionCheckUtils() {
    }

    /**
     * 检测权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkPermission(Context context, String... permissions) {
        for (String permission : permissions) {
            if (!checkPermission(context, permission)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检测权限
     *
     * @param context
     * @param permission
     * @return
     */
    public static boolean checkPermission(Context context, String permission) {
        boolean result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//手机系统版本
            int targetSdkVersion = 9;//必须>= Android M，否则requestPermissions回调中总会返回通过
            try {
                final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                targetSdkVersion = info.applicationInfo.targetSdkVersion;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            //应用targetSdkVersion
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                // targetSdkVersion >= Android M, we can use Context#checkSelfPermission
                result = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
            } else {
                // targetSdkVersion < Android M, we have to use PermissionChecker
                result = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
            }
        } else {
            result = ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
        }

        return result;
    }

    /**
     * 检测录音权限
     *
     * @return true 已授权 false 未授权
     */
    public static boolean checkVoicePermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkPermission(context, Manifest.permission.RECORD_AUDIO);
        }
        // 音频获取源
        int audioSource = MediaRecorder.AudioSource.MIC;
        // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
        int sampleRateInHz = 44100;
        // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
        int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        // 缓冲区字节大小
        int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
        //开始录制音频
        AudioRecord audioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSize);
        try {
            // 防止某些手机崩溃，例如联想
            audioRecord.startRecording();
            int recordingState = audioRecord.getRecordingState();
            // 根据开始录音判断是否有录音权限
            if (recordingState != AudioRecord.RECORDSTATE_RECORDING) {
                return false;
            }
        } catch (Exception e) {
            return false;
        } finally {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
        }
        return true;
    }

    /**
     * 检测安装未知来源APP权限
     *
     * @param context
     * @return
     */
    public static boolean checkUnknownSource(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return context.getPackageManager().canRequestPackageInstalls();
        }
        return true;
    }

    /**
     * 检测通知权限
     *
     * @param context
     * @return
     */
    public static boolean checkNotification(Context context) {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    /**
     * 检测系统弹窗权限
     *
     * @return
     */
    public static boolean checkSystemAlert(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(context);
        }
        try {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int checkResult = manager.checkOpNoThrow(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, Binder.getCallingUid(), context.getPackageName());
            return 0 == checkResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 请求权限
     *
     * @param activity
     * @param requestCode
     * @param permissions
     */
    public static void requestPermissions(Activity activity, String[] permissions, int requestCode) {
        ActivityCompat.requestPermissions(activity, permissions, requestCode);
    }

    /**
     * androidx.fragment.app.Fragment
     * 请求权限
     *
     * @param fragment
     * @param requestCode
     * @param permissions
     */
    public static void requestPermissions(androidx.fragment.app.Fragment fragment, String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            fragment.requestPermissions(permissions, requestCode);
        } else {
            requestPermissions(fragment.getActivity(), permissions, requestCode);
        }
    }

    /**
     * android.app.Fragment
     * 请求权限
     *
     * @param fragment
     * @param requestCode
     * @param permissions
     */
    public static void requestPermissions(android.app.Fragment fragment, String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            fragment.requestPermissions(permissions, requestCode);
        } else {
            requestPermissions(fragment.getActivity(), permissions, requestCode);
        }
    }

    /**
     * 启动应用权限设置页面
     */
    public static void startPermissionSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }
}
